package org.kadicon.android.audio;

import java.io.FileDescriptor;
import java.util.Timer;
import java.util.TimerTask;

import org.kadicon.android.audio.R;

import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.widget.SeekBar;
import android.widget.TextView;

public class MyAudio extends Activity implements
		SeekBar.OnSeekBarChangeListener {

	private final Timer timer = new Timer();
	private MediaPlayer mMediaPlayer;
	private String path = "/sdcard/aa.mp3";
	private SeekBar mSeekBar;
	private TextView mProgressText;
	private TextView mTrackingText;

	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.main);

		mSeekBar = (SeekBar) findViewById(R.id.seek);
		mSeekBar.setOnSeekBarChangeListener(this);
		mProgressText = (TextView) findViewById(R.id.progress);
		mTrackingText = (TextView) findViewById(R.id.tracking);

		playAudio();

		timer.schedule(new TimerTask() {

			@Override
			public void run() {
				int currentPosition = mMediaPlayer.getCurrentPosition();
				int duration = mMediaPlayer.getDuration();
				int per = (int) Math.floor((currentPosition * 100) / duration);
				mSeekBar.setProgress(per);

				if (per == 100) {
					timer.cancel();
				}
			}
		}, 1000, 1000);
	}

	private void playAudio() {
		try {
	        try{
	        	AssetFileDescriptor assetFileDescriptor = getAssets().openFd("Green.mp3");//	        	
	                FileDescriptor fd = assetFileDescriptor.getFileDescriptor();
	                mMediaPlayer = new MediaPlayer();
	                mMediaPlayer.setDataSource(fd); // mp.setDataSource(assetFileDescriptor); You can not pass AssetFileDescriptor.
	                mMediaPlayer.prepare();
	                mMediaPlayer.start();
	        } catch (Exception e) {}      

		} catch (Exception e) {
			Log.e("MyAudio", "error: " + e.getMessage(), e);
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (mMediaPlayer != null) {
			mMediaPlayer.release();
			mMediaPlayer = null;
			timer.cancel();
		}
	}

	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromTouch) {
		mProgressText.setText(progress + "=" + fromTouch);
	}

	public void onStartTrackingTouch(SeekBar seekBar) {
		mTrackingText.setText("on");
	}

	public void onStopTrackingTouch(SeekBar seekBar) {
		mTrackingText.setText("off");
		Log.i("PROGRESS", Integer.toString(seekBar.getProgress()));
		mMediaPlayer.pause();
		int pos = mMediaPlayer.getDuration() * seekBar.getProgress() / 100;
		mMediaPlayer.seekTo(pos);
		mMediaPlayer.start();
	}
}
